package world.criver.h50529.controller;

import javafx.application.Platform;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import world.criver.h50529.application.appStartInform;
import world.criver.h50529.data.daData;
import world.criver.h50529.data.daFun;
import world.criver.h50529.enums.enumComType;
import world.criver.h50529.function.*;
import world.criver.h50529.module.moEvent;
import world.criver.h50529.module.moListen;

import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;

public class conPage1 implements Initializable {
    public Button bu_start;
    public TextArea tip;
    private funHotkey funHotkey=new funHotkey();
    private String hotkeys="";
    private DateTimeFormatter dtf=DateTimeFormatter.ofPattern("[yyyy-MM-dd hh:mm:ss]");
    public void onStart() {
        daData.start_listen=!daData.start_listen;
        bu_start.getStyleClass().clear();
        bu_start.getStyleClass().add(daData.start_listen?"button_listen":"button_await");
        daData.use_port.clear();
        bu_start.setText(daData.start_listen?"停    止":"开    始");
        if(daData.start_listen)funHotkey.addHook();
        else funHotkey.removeHook();
        try {
            if (daData.start_listen) {
                new appStartInform("监听启动", true).start(new Stage());
                daFun.funGroup.startListen();
            }else{
                daFun.funGroup.stopListen();
            }
        }catch (Exception e){}
    }
    public void addTip(String message){
        Platform.runLater(()->{
            tip.appendText(LocalDateTime.now().format(dtf)+"\t"+message+"\n");
        });
    }

    /**
     * 监听到的按键
     * @param key
     */
    public void listenKey(String key) {
        Platform.runLater(() -> {
            hotkeys += (hotkeys.isEmpty() ? "" : "+") + key;
            String[] qw = hotkeys.split("\\+");
            if (qw.length == 0) return;
            else if (qw.length == 1) {
                if (qw[0].equals("Shift") || qw[0].equals("Alt") || qw[0].equals("Windows") || qw[0].equals("Ctrl"))
                    return;
            } else if (qw.length == 2) {
                if (qw[1].equals("Shift") || qw[1].equals("Alt")) return;
            }
            moListen l = null;
            for (moListen mo : daData.listens) {
                if (mo.getHotkey().equals(hotkeys) && !mo.isForbidden()) {
                    l = mo;
                    break;
                }
                if (mo.getHotkey().equals(hotkeys) && mo.isForbidden()) {
                    addTip(">>> 触发 "+mo.getName()+" 热键，但未启用。 <<<");
                    break;
                }
            }
            hotkeys = "";
            if (l == null) return;
            addTip(">>> 触发 " + l.getName() + " 热键：");
            Thread.startVirtualThread(new send(l));
        });
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        Platform.runLater(()->{
            tip.setOnKeyPressed(e->{
                System.out.println(e.getCode().getName()+"("+e.getCode().getCode()+"),");
            });
        });
    }
    private class send implements Runnable{
        private moListen mo;
        public send(moListen listen){
            mo=listen;
        }
        @Override
        public void run() {
            funTcp funTcp=new funTcp();
            funUdp funUdp=new funUdp();
            funWol funWol=new funWol();
            funSerial funSerial=new funSerial();
            for(int i=0;i<mo.getEvents().size();i++){
                long await= (long) (mo.getAwait_time().get(i)*1000);
                try{Thread.sleep(await);}catch (Exception e){}
                moEvent event=null;
                for(moEvent ev:daData.events)if(ev.getName().equals(mo.getEvents().get(i)))event=ev;
                if(event==null)continue;
                addTip("执行事件: "+event.getName());
                String me="",mode=event.getCommunication_mode();
                if(mode.equals(enumComType.com3.name().toUpperCase()))me=funSerial.send(event);
                else if(mode.equals(enumComType.tcp.name().toUpperCase()))me= funTcp.send(event);
                else if(mode.equals(enumComType.udp.name().toUpperCase()))me= funUdp.send(event);
                else if(mode.equals(enumComType.wol.name().toUpperCase()))me= funWol.send(event);
                else me="未找到类型。";
                addTip("执行结果: "+me);
            }
            addTip("<<< 结束 "+mo.getName()+" 热键。");
        }
    }
}
